package cn.com.cfae.iras.doc.analyze.controller;


import cn.com.cfae.iras.doc.analyze.keys.ExtractMethod;
import cn.com.cfae.iras.doc.analyze.parse.PdfParser;
import cn.com.cfae.iras.doc.analyze.parse.model.*;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@RestController
public class PDFExtractorController {

    private static Logger logger = org.slf4j.LoggerFactory.getLogger(PDFExtractorController.class);

    @RequestMapping("/api/v1/extract")
    public String extract(@RequestParam("pdfFilePath") String pdfFilePath, @RequestParam("tableType") String tableType) {

//        try {
//            HanLP.Config.enableDebug(true);
//            HanLP.Config.IOAdapter = new FileIOAdapter();
//            NLPTokenizer.ANALYZER.analyze("我是中国人");
//            System.out.println("加载完成");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        PdfParser pdfParser = new PdfParser();
        pdfParser.parsePdfOutline(new File(pdfFilePath), TableType.M);
        return "{}";
    }

    @RequestMapping("/api/v1/extract/statistics")
    public String statistics(@RequestParam("pdfDirectory") String pdfDirectory, @RequestParam("tableType") String tableType) {

        File file = new File(pdfDirectory);

        File[] pdfFiles = file.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.getName().endsWith(".pdf");
            }
        });

        List<Map<String, StatisticsModel>> statisticsModelMapList = new ArrayList<>();
        PdfParser pdfParser = new PdfParser();
        for (int i = 0; i < pdfFiles.length; i++) {
            File pdfFile = pdfFiles[i];
            long t1 = System.currentTimeMillis();
            logger.info("开始分析文件：{}......", pdfFile.getName());

            DocumentModel documentModel = null;
            try {
//                documentModel = pdfParser.parsePdfOutline(pdfFile, TableType.M);
                documentModel = pdfParser.parsePdfOutline(pdfFile, TableType.DM);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                continue;
            }
            List<ChapterModel> chapterModelList = documentModel.getChapterModels();
            ChapterModel chapterModel = null;
            Map<String, StatisticsModel> statisticsModelMap = new HashMap<>();
            statisticsModelMapList.add(statisticsModelMap);
            for (int j = 0; j < chapterModelList.size(); j++) {
                chapterModel = chapterModelList.get(j);
                if (chapterModel == null) {
                    continue;
                }
                StatisticsModel statisticsModel = new StatisticsModel();
                statisticsModelMap.put(chapterModel.getChapterId(), statisticsModel);
                logger.info("开始分析{}章节抽取模型数量......", chapterModel.getChapterId());
                Map<String, ExtractBizModel> extractBizModelMap = chapterModel.getExtractBizModelMap();
                for (Iterator<String> it = extractBizModelMap.keySet().iterator(); it.hasNext(); ) {
                    String key = it.next();
                    ExtractBizModel extractBizModel = extractBizModelMap.get(key);
                    if (extractBizModel == null) {
                        continue;
                    }

                    logger.info("开始分析{}章节抽取模型数量，业务模型：{}。", chapterModel.getChapterId(), extractBizModel.getModelName());
                    ExtractMethod extractMethod = extractBizModel.getExtractMethods()[0];
                    switch (extractMethod) {
                        case KV:
                            ExtractItem targetExtractItem = null;
                            for (ExtractItem extractItem : extractBizModel.getExtractItemList()) {
                                if (extractItem.getKey() != null) {
                                    targetExtractItem = extractItem;
                                    break;
                                }
                            }
                            if (targetExtractItem != null && (targetExtractItem.getKey() != null || targetExtractItem.getValue() != null)) {
                                statisticsModel.getPassExtractBizModelMap().put(extractBizModel.getModelName(), String.valueOf(true));
                            } else {
                                statisticsModel.getUnpassExtractBizModelMap().put(extractBizModel.getModelName(), String.valueOf(true));
                            }
                            break;
                        case TABLE:
                            if (!extractBizModel.getTables().isEmpty()) {
                                statisticsModel.getPassExtractBizModelMap().put(extractBizModel.getModelName(), String.valueOf(true));
                            } else {
                                statisticsModel.getUnpassExtractBizModelMap().put(extractBizModel.getModelName(), String.valueOf(true));
                            }
                            break;
                        case TABLE_2:
                            if (!extractBizModel.getTables2().isEmpty()) {
                                statisticsModel.getPassExtractBizModelMap().put(extractBizModel.getModelName(), String.valueOf(true));
                            } else {
                                statisticsModel.getUnpassExtractBizModelMap().put(extractBizModel.getModelName(), String.valueOf(true));
                            }
                            break;
                        case TABLE_3:
                            if (!extractBizModel.getTables3().isEmpty()) {
                                statisticsModel.getPassExtractBizModelMap().put(extractBizModel.getModelName(), String.valueOf(true));
                            } else {
                                statisticsModel.getUnpassExtractBizModelMap().put(extractBizModel.getModelName(), String.valueOf(true));
                            }
                            break;
                    }
                }
            }
            long t2 = System.currentTimeMillis();
            logger.info("分析文件：{}完成，耗时：{}毫秒。", pdfFile.getName(), (t2 - t1));
        }

        int count = 0;
        double totalRatio = 0;
        for (Map<String, StatisticsModel> statisticsModelMap : statisticsModelMapList) {
            double totalModel = 0;
            int passTotalModel = 0;
            int unpassTotalModel = 0;
            double passRatio = 0;
            for (Iterator<String> it = statisticsModelMap.keySet().iterator(); it.hasNext(); ) {
                String key = it.next();
                StatisticsModel statisticsModel = statisticsModelMap.get(key);
                passTotalModel += statisticsModel.getPassExtractBizModelMap().size();
                unpassTotalModel += statisticsModel.getUnpassExtractBizModelMap().size();
                totalModel = passTotalModel + unpassTotalModel;
            }
            passRatio = passTotalModel / (totalModel - 7);
            totalRatio += passRatio;
            count++;
        }
        logger.info("分析募集总数：{}，通过率：{}。", count, (totalRatio / count));
        return "{}";
    }

    @RequestMapping("/api/v1/extract/statistics/detail")
    public String statisticsDetail(@RequestParam("pdfDirectory") String pdfDirectory, @RequestParam("tableType") String tableType) {
        File file = new File(pdfDirectory);

        File[] pdfFiles = file.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.getName().endsWith(".pdf");
            }
        });
        StringBuilder stringBuilder = new StringBuilder();
        List<Map<String, StatisticsModel>> statisticsModelMapList = new ArrayList<>();
        PdfParser pdfParser = new PdfParser();
//        List<String> analyzedPdfFiles = new ArrayList<>();
        int count = 0;
        double totalRatio = 0;
        for (int i = 0; i < pdfFiles.length; i++) {
            File pdfFile = pdfFiles[i];
            long t1 = System.currentTimeMillis();
            logger.info("开始分析文件：{}......", pdfFile.getName());

            DocumentModel documentModel = null;
            try {
                documentModel = pdfParser.parsePdfOutline(pdfFile, TableType.M);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                continue;
            }
            stringBuilder.append("====================================START=======================================").append("\n");
            stringBuilder.append("PDF文件名：").append(pdfFile.getAbsolutePath()).append("分析结果：").append("\n");
            List<ChapterModel> chapterModelList = documentModel.getChapterModels();
            ChapterModel chapterModel = null;
            Map<String, StatisticsModel> statisticsModelMap = new HashMap<>();
            statisticsModelMapList.add(statisticsModelMap);
            for (int j = 0; j < chapterModelList.size(); j++) {
                chapterModel = chapterModelList.get(j);
                if (chapterModel == null) {
                    continue;
                }
                stringBuilder.append("章节：").append(chapterModel.getChapterId()).append("\n");
                StatisticsModel statisticsModel = new StatisticsModel();
                statisticsModelMap.put(chapterModel.getChapterId(), statisticsModel);
                logger.info("开始分析{}章节抽取模型数量......", chapterModel.getChapterId());
                Map<String, ExtractBizModel> extractBizModelMap = chapterModel.getExtractBizModelMap();
                for (Iterator<String> it = extractBizModelMap.keySet().iterator(); it.hasNext(); ) {
                    String key = it.next();
                    ExtractBizModel extractBizModel = extractBizModelMap.get(key);
                    if (extractBizModel == null) {
                        continue;
                    }
                    logger.info("开始分析{}章节抽取模型数量，业务模型：{}。", chapterModel.getChapterId(), extractBizModel.getModelName());
                    ExtractMethod extractMethod = extractBizModel.getExtractMethods()[0];
                    try {
                        switch (extractMethod) {
                            case KV:
                                ExtractItem targetExtractItem = null;
                                for (ExtractItem extractItem : extractBizModel.getExtractItemList()) {
                                    if (extractItem.getKey() != null) {
                                        targetExtractItem = extractItem;
                                        break;
                                    }
                                }
                                if (targetExtractItem != null && targetExtractItem.getKey() != null) {
                                    statisticsModel.getPassExtractBizModelMap().put(extractBizModel.getModelName(), String.valueOf(true));
                                    stringBuilder.append("模型名称：").append(extractBizModel.getModelName()).append("，抽取结果：").append(true).append("\n");
                                } else {
                                    statisticsModel.getUnpassExtractBizModelMap().put(extractBizModel.getModelName(), String.valueOf(false));
                                    stringBuilder.append("模型名称：").append(extractBizModel.getModelName()).append("，抽取结果：").append(false).append("\n");
                                }
                                break;
                            case TABLE:
                                if (!extractBizModel.getTables().isEmpty()) {
                                    statisticsModel.getPassExtractBizModelMap().put(extractBizModel.getModelName(), String.valueOf(true));
                                    stringBuilder.append("模型名称：").append(extractBizModel.getModelName()).append("，抽取结果：").append(true).append("\n");
                                } else {
                                    statisticsModel.getUnpassExtractBizModelMap().put(extractBizModel.getModelName(), String.valueOf(false));
                                    stringBuilder.append("模型名称：").append(extractBizModel.getModelName()).append("，抽取结果：").append(false).append("\n");
                                }
                                break;
                            case TABLE_2:
                                if (!extractBizModel.getTables2().isEmpty()) {
                                    statisticsModel.getPassExtractBizModelMap().put(extractBizModel.getModelName(), String.valueOf(true));
                                    stringBuilder.append("模型名称：").append(extractBizModel.getModelName()).append("，抽取结果：").append(true).append("\n");
                                } else {
                                    statisticsModel.getUnpassExtractBizModelMap().put(extractBizModel.getModelName(), String.valueOf(false));
                                    stringBuilder.append("模型名称：").append(extractBizModel.getModelName()).append("，抽取结果：").append(false).append("\n");
                                }
                                break;
                            case TABLE_3:
                                if (!extractBizModel.getTables3().isEmpty()) {
                                    statisticsModel.getPassExtractBizModelMap().put(extractBizModel.getModelName(), String.valueOf(true));
                                    stringBuilder.append("模型名称：").append(extractBizModel.getModelName()).append("，抽取结果：").append(true).append("\n");
                                } else {
                                    statisticsModel.getUnpassExtractBizModelMap().put(extractBizModel.getModelName(), String.valueOf(false));
                                    stringBuilder.append("模型名称：").append(extractBizModel.getModelName()).append("，抽取结果：").append(false).append("\n");
                                }
                                break;
                        }
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                }
            }
            stringBuilder.append("=====================单个抽取率统计如下：=======================").append("\n");
            double totalModel = 0;
            int passTotalModel = 0;
            int unpassTotalModel = 0;
            double passRatio = 0;
            for (Iterator<String> it = statisticsModelMap.keySet().iterator(); it.hasNext(); ) {
                String key = it.next();
                StatisticsModel statisticsModel = statisticsModelMap.get(key);
                if (statisticsModel == null) {
                    continue;

                }
                passTotalModel += statisticsModel.getPassExtractBizModelMap().size();
                unpassTotalModel += statisticsModel.getUnpassExtractBizModelMap().size();
                totalModel = passTotalModel + unpassTotalModel;
            }
            passRatio = passTotalModel / (totalModel - 9);
            totalRatio += passRatio;
            count++;
            String statisticsString = String.format("单个文档抽取率统计，业务指标模型共计：%s，已抽取：%s，抽取率：%s。", (totalModel - 9), passTotalModel, passRatio);
            stringBuilder.append(statisticsString).append("\n");
            stringBuilder.append("====================================END=======================================").append("\n");
            long t2 = System.currentTimeMillis();
            logger.info("分析文件：{}完成，耗时：{}毫秒。", pdfFile.getName(), (t2 - t1));
        }

//        for (Map<String, StatisticsModel> statisticsModelMap : statisticsModelMapList) {
//            double totalModel = 0;
//            int passTotalModel = 0;
//            int unpassTotalModel = 0;
//            double passRatio = 0;
//            for (Iterator<String> it = statisticsModelMap.keySet().iterator(); it.hasNext(); ) {
//                String key = it.next();
//                StatisticsModel statisticsModel = statisticsModelMap.get(key);
//                if (statisticsModel == null) {
//                    continue;
//
//                }
//                passTotalModel += statisticsModel.getPassExtractBizModelMap().size();
//                unpassTotalModel += statisticsModel.getUnpassExtractBizModelMap().size();
//                totalModel = passTotalModel + unpassTotalModel;
//            }
//            passRatio = passTotalModel / (totalModel - 7);
//            totalRatio += passRatio;
//            count++;
//        }
        logger.info("分析募集总数：{}，通过率：{}。", count, (totalRatio / count));
        stringBuilder.append("\n").append("分析募集总数：").append(count).append("，通过率：").append(totalRatio / count);
        System.out.println("打印抽取统计结果：");
        System.out.println(stringBuilder.toString());
        try {
            FileUtils.write(new File("/Users/WangYanqing/Temp/sm/statistics-" + System.currentTimeMillis() + ".dat"), stringBuilder.toString());
//            FileUtils.write(new File("./statistics-" + System.currentTimeMillis() + ".dat"), stringBuilder.toString());
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return "{}";
    }
}
